package com.xoms.admin.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.xoms.admin.cache.dao.ResourceCache;
import com.xoms.admin.controller.res.bean.RAccountRolesBean;
import com.xoms.admin.controller.res.bean.RRoleBean;
import com.xoms.admin.model.AccountBean;
import com.xoms.admin.model.RoleBean;
import com.xoms.admin.persist.dao.ProCategoryDao;
import com.xoms.admin.persist.dao.ResourceDao;
import com.xoms.admin.persist.dao.RoleDao;
import com.xoms.admin.service.RoleService;
import com.xoms.admin.service.exception.ServiceException;
import com.xoms.admin.service.res.PageResult;
import com.xoms.util.DateTimeUtil;

@Service
public class RoleServiceImpl implements RoleService {
	
	Logger logger = Logger.getLogger(this.getClass());

	@Autowired
	RoleDao roleImpl;
	
	@Autowired
	ResourceDao resourceImpl;
	
	@Autowired
	ResourceCache resourceCacheImpl;
	
	@Autowired
	ProCategoryDao proCategoryImpl;
	
	@Override
	public PageResult<RAccountRolesBean> getAccountRoles(AccountBean account, String accId) {
		PageResult<RAccountRolesBean> result = new PageResult<RAccountRolesBean>();
		List<RAccountRolesBean> resList = new ArrayList<RAccountRolesBean>();
		// 获取用户权限数量
		int count = roleImpl.selectCount2Account(accId);
		if (count > 0) {
			// 数量不为0时获取权限列表
			List<RoleBean> lists = roleImpl.selectRoles2Account(accId);

			if (lists != null) {
				RAccountRolesBean rar = null;
				for (RoleBean res : lists) {
					rar = new RAccountRolesBean();
					rar.setRoleId(res.getRoleId());
					rar.setRoleName(res.getName());
					resList.add(rar);
				}
			}
		}
		result.setData(resList);
		result.setCount(resList.size());
		return result;
	}

	@Override
	public RRoleBean edit(AccountBean account, int roleId, String name, int isEnable, String desc, int sort) {
		RoleBean data = new RoleBean();
		boolean flag = false;
		data.setName(name);
		data.setStatus(isEnable);
		data.setRemark(desc);
		data.setSort(sort);
		if (roleId == -1) {// 新建
			
			data.setAccountId(account.getAccid());
			flag = roleImpl.insert(data) > 0;
			if (!flag) {
				throw new ServiceException("database_insert_fail","角色信息");
			}
		} else {
			data.setRoleId(roleId);
			flag = roleImpl.update(data) > 0;// 更新数据库
			if (!flag) {
				throw new ServiceException("database_update_fail","角色信息");
			}
		}
		return parse(roleImpl.selectOneById(data.getRoleId()));
	
	}
	
	/**
	 * 格式化数据
	 * @param role
	 * @return
	 */
	private RRoleBean parse(RoleBean role) {
		RRoleBean res = new RRoleBean();
		res.setId(role.getRoleId());
		res.setName(role.getName());
		res.setIsEnable(role.getStatus());
		res.setDesc(role.getRemark());
		res.setCreateTime(DateTimeUtil.formatTimestamp(role.getCreateTime()));
		res.setUpdateTime(DateTimeUtil.formatTimestamp(role.getUpdateTime()));
		return res;
	}

	@Override
	public boolean enable(AccountBean account, int roleId) {
		if (roleImpl.updateStatus(roleId, 1) > 0) {// 更新状态
			return true;
		}

		return false;
	}

	@Override
	public boolean disable(AccountBean account, int roleId) {
		if (roleImpl.updateStatus(roleId, 0) > 0) {// 更新状态
			return true;
		}

		return false;
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public boolean del(AccountBean account, int roleId) {
		boolean flag = false;
		// 删除角色
		//	1判断有无用户拥有该角色
		int accNum = roleImpl.selectAccNum2Role(roleId);
		if(accNum > 0) {// 有用户拥有该角色，则删除关联关系
			flag = roleImpl.delAllRoleRelation(roleId) > 0;
			if(!flag) {
				throw new ServiceException("database_delete_fail","用户角色关系");
			}
		}
		//	2判断有无关联权限
		int resNum = roleImpl.selectResNum2Role(roleId);
		if(resNum > 0) {
			flag = roleImpl.delAllResRelation2Role(roleId) > 0;
			if(!flag) {
				throw new ServiceException("database_delete_fail","角色权限关系");
			}
		}
		flag = roleImpl.del(roleId) > 0;// 删除角色状态
		if(!flag) {
			throw new ServiceException("database_delete_fail","权限信息");
		}

		return flag;
	}

	@Override
	public PageResult<RRoleBean> getRoles(AccountBean account, String key, int page, int pagesize) {
		PageResult<RRoleBean> result = new PageResult<RRoleBean>();
		List<RRoleBean> resList = new ArrayList<RRoleBean>();
		// 获取角色数量
		int count = roleImpl.selectCount(key);
		if (count > 0) {
			// 数量不为0时获取角色列表
			List<RoleBean> lists = roleImpl.selectList(key, page, pagesize);

			if (lists != null) {
				RRoleBean rr = null;
				for (RoleBean res : lists) {
					rr = new RRoleBean();
					rr = parse(res);
					resList.add(rr);
				}
			}
		}
		result.setData(resList);
		result.setCount(count);
		return result;
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public boolean addRoleResources(AccountBean account, int roleId, String resourceIds) {
		boolean flag = false;
		String[] rids =  resourceIds.replaceAll("\\[|\\]|\"", "").split(",");
		// 如果赋值的权限不为空，则将全部角色权限关联插入数据库
		if(rids != null && rids.length > 0) {
			// 2将角色权限关系批量插入数据库
			flag = roleImpl.insertRoleResources(account.getAccid(), roleId, rids) > 0;
			if (!flag) {
				throw new ServiceException("database_insert_fail","角色权限关联");
			}
			//throw new ServiceException("edit_resources_is_null");
			// 3 清除redis缓存
			resourceCacheImpl.clearRoleResource(roleId);
			
		}
		return flag;
	}

	@Override
	public boolean editSorts2Role(String sorts, int page, int pagesize) {
		boolean flag = false;
		List<String> sortList = JSON.parseArray(sorts, String.class);
		flag = roleImpl.updateSorts(sortList, page, pagesize) > 0;
		return flag;
	}
	
	@Transactional(rollbackFor = Exception.class)
	@Override
	public boolean addAcountRoles(AccountBean account, String accid, String roleIds) {
		boolean flag = false;
		String[] rids =  roleIds.replaceAll("\\[|\\]|\"", "").split(",");
		if(rids != null && rids.length > 0) {
			// 将账号角色关系批量插入数据库
			flag = roleImpl.insertAccountRoles(account.getAccid(), accid, rids) > 0;
			if (!flag) {
				throw new ServiceException("database_insert_fail","账号角色信息");
			}
			// 清除redis缓存
			resourceCacheImpl.clearAccountResource(accid);
		} else {
			throw new ServiceException("object_is_not_exist","添加的账号角色");
		}
		return flag;
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public boolean delAcountRoles(AccountBean account, String accid, String roleIds) {
		boolean flag = false;
		// 删除账号对应权限
		String[] rids =  roleIds.replaceAll("\\[|\\]|\"", "").split(",");
		if(rids != null && rids.length > 0) {
			flag = roleImpl.delAccountRoles(accid, rids) > 0;
			if (!flag) {
				throw new ServiceException("database_delete_fail","账号角色信息");
			}
			// 清除redis缓存
			resourceCacheImpl.clearAccountResource(accid);
		} else {
			throw new ServiceException("object_is_not_exist","删除的账号角色");
		}
		return flag;
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public boolean delRoleResources(AccountBean account, int roleId, String resourceIds) {
		boolean flag = false;
		// 删除账号对应权限
		String[] rids =  resourceIds.replaceAll("\\[|\\]|\"", "").split(",");
		if(rids != null && rids.length > 0) {
			flag = roleImpl.delRoleResources(roleId, rids) > 0;
			if (!flag) {
				throw new ServiceException("database_delete_fail","角色资源信息");
			}
			// 清除redis缓存
			resourceCacheImpl.clearRoleResource(roleId);
		} else {
			throw new ServiceException("object_is_not_exist","删除的角色资源");
		}
		
		return flag;
	}


}